<template>
  <view class="register-container">
    <!-- 导航栏 -->
    <up-navbar :title="''" left-icon-color="#ffffff" bg-color="transparent" :border="false" :safeAreaInsetTop="true" :autoBack="true">
      <template #right>
        <view class="language-btn" @click="goToLanguagePage">
          <u-icon name="/static/login/language.png" size="40rpx" color="#12c284"></u-icon>
        </view>
      </template>
    </up-navbar>

    <!-- 主要内容区域 -->
    <view class="main-content">
      <!-- 品牌标识 -->
      <view class="brand-section">
        <view class="logo">
          <image class="logo-image" src="/static/logo.png" mode="aspectFit" />
        </view>
        <view class="brand-name">
          <text class="brand-title">NEXA</text>
          <text class="brand-subtitle">EXWORTH</text>
        </view>
      </view>

      <!-- 输入区域 -->
      <view class="input-section">
        <!-- 邮箱输入框 -->
        <view class="input-group">
          <view class="input-wrapper">
            <input class="input-field" type="text" :placeholder="useT('输入邮箱')" v-model="email" />
          </view>
        </view>

        <!-- 验证码输入框 -->
        <view class="input-group">
          <view class="input-wrapper">
            <input class="input-field" type="number" :placeholder="useT('输入验证码')" v-model="verificationCode" maxlength="6" />
            <view class="get-code-btn" @click="getVerificationCode">
              <text class="get-code-text">{{ countdown > 0 ? countdown + 's' : useT('验证码') }}</text>
            </view>
          </view>
        </view>

        <!-- 密码输入框 -->
        <view class="input-group">
          <view class="input-wrapper">
            <input class="input-field" type="password" :placeholder="useT('输入密码(6-32位)')" v-model="password" maxlength="32" />
          </view>
        </view>

        <!-- 邀请码输入框 -->
        <view class="input-group">
          <text class="invite-label">
            <text class="required-mark">*</text>
            {{ useT('邀请码') }}
          </text>
          <view class="input-wrapper">
            <input class="input-field" type="text" :placeholder="useT('邀请码')" v-model="inviteCode" />
          </view>
        </view>
      </view>

      <!-- 注册按钮 -->
      <view class="next-btn-wrapper">
        <view class="next-btn" @click="handleRegister">
          <text class="next-btn-text">{{ useT('立即注册') }}</text>
        </view>
      </view>

      <!-- 用户协议 -->
      <view class="agreement-section">
        <view class="agreement-checkbox" @click="toggleAgreement">
          <view class="checkbox" :class="{ checked: isAgreed }">
            <text class="checkmark" v-if="isAgreed">✓</text>
          </view>
          <text class="agreement-text">
            {{ useT('已阅读并同意') }}
            <text class="link-text" @click.stop="showUserAgreement">{{ useT('《用户协议》') }}</text>
            &
            <text class="link-text" @click.stop="showPrivacyPolicy">{{ useT('服务协议与隐私政策') }}</text>
          </text>
        </view>
      </view>
    </view>

    <!-- 协议弹窗 -->
    <up-popup v-model:show="showAgreementPopup" mode="center" :round="20" :closeable="false" :closeOnClickOverlay="false">
      <view class="agreement-popup">
        <view class="popup-title">{{ useT('服务协议与隐私政策') }}</view>
        <view class="popup-content">
          <text>{{ useT('已阅读并同意') }}</text>
          <text class="link-text" @click.stop="showUserAgreement">{{ useT('《用户协议》') }}</text>
          <text>&</text>
          <text class="link-text" @click.stop="showPrivacyPolicy">{{ useT('服务协议与隐私政策') }}</text>
        </view>
        <view class="popup-buttons">
          <up-button type="default" :text="useT('取消')" :custom-style="{ width: '200rpx', height: '80rpx', marginRight: '20rpx' }" @click="closeAgreementPopup" />
          <up-button type="primary" :text="useT('我同意')" :custom-style="{ width: '200rpx', height: '80rpx' }" @click="agreeAndRegister" />
        </view>
      </view>
    </up-popup>
  </view>
</template>

<script setup>
import { registerBySms, sendSmsCode, SMS_EVENTS, validateCaptcha } from '@/api/login.js';
import { goToWebView } from '@/config/webViewConfig.js';
import { useT } from '@/utils/i18n.js';
import { onMounted, onUnmounted, ref } from 'vue';

// 响应式数据
const email = ref('');
const verificationCode = ref('');
const password = ref('');
const inviteCode = ref('');
const isAgreed = ref(false);
const countdown = ref(0);
const timer = ref(null);
const showAgreementPopup = ref(false); // 控制协议弹窗显示

// 生命周期钩子
onMounted(() => {
  // 页面加载
});

onUnmounted(() => {
  // 清理定时器
  if (timer.value) {
    clearInterval(timer.value);
  }
});

// 邮箱验证函数
const validateEmail = (email) => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return emailRegex.test(email);
};

// 密码验证函数（6-32位）
const validatePassword = (password) => {
  if (!password || password.trim() === '') {
    return false;
  }
  const length = password.length;
  return length >= 6 && length <= 32;
};

// 跳转到语言选择页面
const goToLanguagePage = () => {
  uni.navigateTo({
    url: '/pagesD/setting/language'
  });
};

// 获取验证码
const getVerificationCode = async () => {
  if (countdown.value > 0) return;

  // 验证邮箱格式
  if (!validateEmail(email.value)) {
    uni.showToast({
      title: useT('请输入正确的邮箱'),
      icon: 'none'
    });
    return;
  }

  try {
    uni.showLoading({
      title: useT('发送中.')
    });

    // 调用发送验证码API（注册类型）
    const result = await sendSmsCode({
      phone: email.value, // 字段名保持phone，但传邮箱值
      type: SMS_EVENTS.REGISTER
    });

    uni.hideLoading();
    console.log('====>result', result);

    if (result.status === 200) {
      // 开始倒计时
      countdown.value = 60;
      timer.value = setInterval(() => {
        countdown.value--;
        if (countdown.value <= 0) {
          clearInterval(timer.value);
          timer.value = null;
        }
      }, 1000);

      uni.showToast({
        title: result.msg,
        icon: 'success'
      });
    }
  } catch (error) {
    console.log('====>error', error);
    uni.hideLoading();
  }
};

// 处理注册
const handleRegister = () => {
  // 验证邮箱格式
  if (!validateEmail(email.value)) {
    uni.showToast({
      title: useT('请输入正确的邮箱'),
      icon: 'none'
    });
    return;
  }

  // 检查验证码
  if (!validateCaptcha(verificationCode.value)) {
    uni.showToast({
      title: useT('请输入6位验证码'),
      icon: 'none'
    });
    return;
  }

  // 检查密码
  if (!validatePassword(password.value)) {
    uni.showToast({
      title: useT('请输入6-32位密码'),
      icon: 'none'
    });
    return;
  }

  // 检查邀请码
  if (!inviteCode.value || inviteCode.value.trim() === '') {
    uni.showToast({
      title: useT('请输入邀请码'),
      icon: 'none'
    });
    return;
  }

  // 检查协议是否同意
  if (!isAgreed.value) {
    showAgreementModal();
    return;
  }

  // 执行注册
  performRegister();
};

// 显示协议弹窗
const showAgreementModal = () => {
  showAgreementPopup.value = true;
};

// 关闭协议弹窗
const closeAgreementPopup = () => {
  showAgreementPopup.value = false;
};

// 同意协议并注册
const agreeAndRegister = () => {
  // 自动勾选协议
  isAgreed.value = true;
  // 关闭弹窗
  showAgreementPopup.value = false;
  // 等待1秒后注册
  setTimeout(() => {
    performRegister();
  }, 1000);
};

// 执行注册
const performRegister = async () => {
  uni.showLoading({
    title: useT('注册中.')
  });

  try {
    // 邮箱验证码注册
    const result = await registerBySms({
      phone: email.value, // 字段名保持phone，但传邮箱值
      captcha: verificationCode.value,
      pwd: password.value,
      spread: inviteCode.value.trim()
    });

    uni.hideLoading();
    console.log('====>result', result);
    if (result.status === 200) {
      uni.showToast({
        title: useT('注册成功'),
        icon: 'success'
      });

      // 注册成功后跳转到登录
      setTimeout(() => {
        uni.navigateTo({
          url: '/pages/login/login'
        });
      }, 1500);
    }
  } catch (error) {
    console.log('====>error', error);
    uni.hideLoading();
    uni.showToast({
      title: error || useT('注册失败，请重试'),
      icon: 'none'
    });
  }
};

// 切换协议同意状态
const toggleAgreement = () => {
  isAgreed.value = !isAgreed.value;
};

// 显示用户协议
const showUserAgreement = () => {
  goToWebView('userAgreement');
};

// 显示隐私政策
const showPrivacyPolicy = () => {
  goToWebView('privacyPolicy');
};
</script>

<style lang="scss" scoped>
.register-container {
  min-height: 100vh;
  background: #000000;
  position: relative;
}

.status-bar {
  height: var(--status-bar-height);
  background: #000000;
}

.language-btn {
  display: flex;
  align-items: center;
  justify-content: center;
}

.main-content {
  padding: 60rpx 40rpx 40rpx;
  min-height: calc(100vh - var(--status-bar-height));
  box-sizing: border-box;
}

// 品牌标识
.brand-section {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 120rpx;
  margin-bottom: 80rpx;

  .logo {
    margin-right: 24rpx;

    .logo-image {
      width: 120rpx;
      height: 120rpx;
      border-radius: 12rpx;
    }
  }

  .brand-name {
    display: flex;
    flex-direction: column;

    .brand-title {
      font-size: 48rpx;
      font-weight: bold;
      color: #ffffff;
      line-height: 1;
      margin-bottom: 8rpx;
    }

    .brand-subtitle {
      font-size: 32rpx;
      color: #ffffff;
      line-height: 1;
    }
  }
}

// 输入区域
.input-section {
  margin-bottom: 60rpx;

  .input-group {
    margin-bottom: 40rpx;

    .input-wrapper {
      display: flex;
      align-items: center;
      background: #333333;
      border-radius: 12rpx;
      padding: 0 24rpx;
      height: 88rpx;
      position: relative;

      .input-field {
        flex: 1;
        height: 100%;
        font-size: 32rpx;
        color: #ffffff;
        background: transparent;
        border: none;
        outline: none;
      }

      .input-field::placeholder {
        color: #999999;
      }

      .get-code-btn {
        position: absolute;
        right: 24rpx;
        top: 50%;
        transform: translateY(-50%);
        padding: 8rpx 16rpx;
        background: #ffffff;
        border-radius: 8rpx;
        cursor: pointer;

        .get-code-text {
          color: #000000;
          font-size: 28rpx;
          font-weight: 500;
        }
      }
    }

    .input-hint {
      color: #999999;
      font-size: 24rpx;
      margin-top: 16rpx;
      display: block;
    }

    .invite-label {
      color: #ffffff;
      font-size: 28rpx;
      margin-bottom: 16rpx;
      display: block;

      .required-mark {
        color: #ff4444;
        margin-right: 4rpx;
      }
    }
  }
}

// 下一步按钮
.next-btn-wrapper {
  margin-bottom: 60rpx;

  .next-btn {
    width: 100%;
    height: 88rpx;
    background: #ffffff;
    border-radius: 12rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;

    .next-btn-text {
      color: #000000;
      font-size: 32rpx;
      font-weight: 500;
    }
  }
}

// 用户协议
.agreement-section {
  display: flex;
  align-items: center;
  justify-content: center;

  .agreement-checkbox {
    display: flex;
    align-items: center;
    cursor: pointer;

    .checkbox {
      width: 32rpx;
      height: 32rpx;
      border: 2rpx solid #cccccc;
      border-radius: 50%;
      margin-right: 16rpx;
      margin-top: 4rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      flex-shrink: 0;

      &.checked {
        background: #ffffff;
        border-color: #ffffff;
      }

      .checkmark {
        color: #000000;
        font-size: 20rpx;
        font-weight: bold;
      }
    }

    .agreement-text {
      font-size: 24rpx;
      color: #999999;
      line-height: 1.5;
      flex: 1;

      .link-text {
        color: #ffffff;
        text-decoration: underline;
      }
    }
  }
}

// 协议弹窗
.agreement-popup {
  padding: 60rpx 40rpx 40rpx;
  width: 600rpx;
  text-align: center;
  background: #ffffff;
  border-radius: 20rpx;

  .popup-title {
    font-size: 36rpx;
    font-weight: bold;
    color: #333333;
    margin-bottom: 30rpx;
  }

  .popup-content {
    font-size: 28rpx;
    color: #666666;
    line-height: 1.6;
    margin-bottom: 50rpx;

    .link-text {
      color: #4a90e2;
      text-decoration: underline;
      margin: 0 8rpx;
    }
  }

  .popup-buttons {
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
</style>
